package leetcode.easy.getIntersectionNode;

import util.adt.ListNode;
import util.annotation.Solved;

/**
 * <a href="https://leetcode.cn/problems/intersection-of-two-linked-lists/description/?envType=study-plan-v2&envId=
 * top-100-liked">160. 相交链表</a>
 */
@Solved
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode pa = headA;
        ListNode pb = headB;
        // 任何一个是空列表都不会存在相同的节点
        if (pa == null || pb == null) {
            return null;
        }
        // 遍历
        while (true) {
            if (pa == pb) {
                return pa;
            }
            if (pa == null && pb == null) {
                return null;
            }
            if (pa == null) {
                pa = headB;
                pb = pb.next;
                continue;
            }
            if (pb == null) {
                pb = headA;
                pa = pa.next;
                continue;
            }
            pa = pa.next;
            pb = pb.next;
        }
    }
}
